# -*- coding: utf-8 -*-
# @Time: 2021/11/30 9:12
# @Author: jiuwu
# @Email: 2359196586@qq.com
# @File: permission.py
# @Software: PyCharm
# 定义装饰器 判断当前登录用户和创建用户是否匹配
from rest_framework.response import Response


def create_user_auto(func):
    def f(self, request, *args, **kwargs):
        request.POST._mutable = True
        request.data['user'] = str(request.user.id)
        return func(self, request, *args, **kwargs)

    return f


def update_user_auto(classes):
    def wrapper(func):
        def f(self, request, *args, **kwargs):
            if not classes.objects.filter(id=kwargs['pk'], user=request.user):
                return Response({'detail': '您没有修改权限'})

            request.POST._mutable = True
            request.data['user'] = str(request.user.id)
            return func(self, request, *args, **kwargs)

        return f

    return wrapper


def destroy_user_auto(classes):
    def wrapper(func):
        def f(self, request, *args, **kwargs):
            if not classes.objects.filter(id=kwargs['pk'], user=request.user):
                return Response({'detail': '您没有删除权限'})

            return func(self, request, *args, **kwargs)

        return f

    return wrapper
